package com.netflix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@SpringBootApplication
public class SpringcloudNetflixRibbonConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudNetflixRibbonConsumerApplication.class, args);
    }

    @Configuration
    public class RestTemplateConfiguration{
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }

    @RestController
    static class TestController{
        @Resource
        private RestTemplate restTemplate;
        @Resource
        private LoadBalancerClient loadBalancerClient;

        @GetMapping("/hello")
        public String hello(String name){
            ServiceInstance serviceInstance=loadBalancerClient.choose("demo-provider");
            String url=serviceInstance.getUri()+"/test?name="+name;
            String response=restTemplate.getForObject(url,String.class);
            return "consumer:"+response;
        }

        @GetMapping("/hello2")
        public String hello2(String name){
            String url="http://demo-provider/test?name=" + name;
            String response=restTemplate.getForObject(url,String.class);
            return "consumer:"+response;
        }
    }

}
